package me.zhengjie.modules.xiao.rest;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.UserQueryCriteria;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.xiao.domain.CgCustomertable;
import me.zhengjie.modules.xiao.domain.CgFollowupform;
import me.zhengjie.modules.xiao.domain.CgSigningform;
import me.zhengjie.modules.xiao.domain.dto.CgCustomertableCountDTO;
import me.zhengjie.modules.xiao.domain.vo.CgCheckVo;
import me.zhengjie.modules.xiao.domain.vo.CgCustomertableQueryCriteria;
import me.zhengjie.modules.xiao.domain.vo.CgNatureVo;
import me.zhengjie.modules.xiao.service.*;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.VxMsg;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DatePattern.NORM_DATE_PATTERN;

/**
* @author cg
* @date 2024-06-19
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "客户表管理")
@RequestMapping("/api/cgCustomertable")
public class CgCustomertableController {

    private final CgCluetableService cgCluetableService;
    private final CgCustomertableService cgCustomertableService;
    private final CgDesignService cgDesignService;
    private final CgFollowupformService cgFollowupformService;
    private final CgSigningformService cgSigningformService;

    private final UserService userService;
    private final DeptService deptService;
    private final VxMsg vxMsg;
    private final DictDetailService dictDetailService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('cgCustomertable:list')")
    public void exportCgCustomertable(HttpServletResponse response, CgCustomertableQueryCriteria criteria) throws IOException {
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        List<Long> jobs = userDetails.getUser().getJobs().stream().map(Job::getId).collect(Collectors.toList());
        Long deptId = userDetails.getUser().getDept().getId();
        Integer level = userDetails.getLevel();
        if(jobs.contains(8L)){
            if (level == 3||level == 4) {
                UserQueryCriteria userCriteria = new UserQueryCriteria();
                List<Dept> data = deptService.findByPid(deptId);
                // 然后把子节点的ID都加入到集合中
                userDetails.getDataScopes().get(0);
                List<Long> deptIds = deptService.getDeptChildren(data);
                deptIds.add(deptId);
                deptIds.retainAll(userDetails.getDataScopes());
                userCriteria.getDeptIds().addAll(deptIds);
                if(level == 3){
                   deptIds.add(0L);
                }
                criteria.getDeptIds().addAll(deptIds);
                criteria.getCreateBys().add(userDetails.getUser().getUsername());
            }
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }
        if(StringUtils.isNotBlank(criteria.getTime())){
            List<Date> createTimeList = new ArrayList<>();
            Date date = DateUtil.parse(criteria.getTime(),NORM_DATE_PATTERN);
            createTimeList.add( DateUtil.beginOfDay(date));
            createTimeList.add( DateUtil.endOfDay(date));
            criteria.setCreateTimeList(createTimeList);
        }
        cgCustomertableService.download(cgCustomertableService.queryAll(criteria), response);
    }

    @GetMapping(value = "/page")
    @Log("查询客户表")
    @ApiOperation("查询客户表")
    @PreAuthorize("@el.check('cgCustomertable:list')")
    public ResponseEntity<PageResult<CgCustomertable>> queryCgCustomertable(CgCustomertableQueryCriteria criteria, Page<Object> page){
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        List<Long> jobs = userDetails.getUser().getJobs().stream().map(Job::getId).collect(Collectors.toList());
        Long deptId = userDetails.getUser().getDept().getId();
        Integer level = userDetails.getLevel();
        if(jobs.contains(8L)){
            if (level == 3||level == 4) {
                UserQueryCriteria userCriteria = new UserQueryCriteria();
                List<Dept> data = deptService.findByPid(deptId);
                // 然后把子节点的ID都加入到集合中
                userDetails.getDataScopes().get(0);
                List<Long> deptIds = deptService.getDeptChildren(data);
                deptIds.add(deptId);
                deptIds.retainAll(userDetails.getDataScopes());
                userCriteria.getDeptIds().addAll(deptIds);
                if(level == 3){
                   deptIds.add(0L);
                }
                criteria.getDeptIds().addAll(deptIds);
                criteria.getCreateBys().add(userDetails.getUser().getUsername());
            }
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }

        if(StringUtils.isNotBlank(criteria.getTime())){
            List<Date> createTimeList = new ArrayList<>();
            Date date = DateUtil.parse(criteria.getTime(),NORM_DATE_PATTERN);
            createTimeList.add( DateUtil.beginOfDay(date));
            createTimeList.add( DateUtil.endOfDay(date));
            criteria.setCreateTimeList(createTimeList);
        }

        PageResult<CgCustomertable> pageResult = cgCustomertableService.queryAll(criteria,page);
        for(CgCustomertable cgCustomertable:pageResult.getContent()){
                if (!jobs.contains(8L)) {
                    cgCustomertable.setMessageStatus("2");
                }
                User user = userService.findByName(cgCustomertable.getCreateBy());
                if (user !=null){
                    cgCustomertable.setCreateUserName(user.getNickName());
                }

        }
        return new ResponseEntity<>(pageResult,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增客户表")
    @ApiOperation("新增客户表")
    @PreAuthorize("@el.check('cgCustomertable:add')")
    public ResponseEntity<Object> createCgCustomertable(@Validated @RequestBody CgCustomertable resources){
        String userName = SecurityUtils.getCurrentUsername();
        Long createdeptId = SecurityUtils.getCurrentDeptId();
        String createdeptName = SecurityUtils.getCurrentDeptName();
        List<CgFollowupform> listFoll = cgFollowupformService.findByPhone(resources.getCustomerTel());
        String followStatus = listFoll.isEmpty()?"1":"2";
        resources.setFollowStatus(followStatus);

        List<CgSigningform> listSign = cgSigningformService.findByPhone(resources.getCustomerTel());
        String signStatus = listSign.isEmpty()?"1":"2";
        resources.setSignStatus(signStatus);
        resources.setMessageStatus("1");
        resources.setCreateBy(userName);
        resources.setCreateTime(DateUtil.date().toTimestamp());
        resources.setCreateDeptId(createdeptId);
        resources.setCreateDeptName(createdeptName);
        cgCustomertableService.create(resources);
        DictDetail dictDetail = dictDetailService.getById(22);
        if("1".equals(dictDetail.getValue())){
            Integer type = "1".equals(resources.getCustomerFlag())?1:3;
            List<String> usernames = userService.getUserNameByDeptId(resources.getDeptId());
            for(String sendUserName:usernames){
                vxMsg.sendCustomerMsg(sendUserName,resources.getId(),type,resources.getCustomerName(),DateUtil.formatDate(new Date()));
            }
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping
    @Log("修改客户表")
    @ApiOperation("修改客户表")
    @PreAuthorize("@el.check('cgCustomertable:edit')")
    public ResponseEntity<Object> updateCgCustomertable(@Validated @RequestBody CgCustomertable resources){
        String userName = SecurityUtils.getCurrentUsername();
        List<CgFollowupform> listFoll = resources.getListFoll();
        String followStatus = listFoll.isEmpty()?"1":"2";
        resources.setFollowStatus(followStatus);

        List<CgSigningform> listSign = resources.getListSign();
        String signStatus = listSign.isEmpty()?"1":"2";
        resources.setSignStatus(signStatus);
        resources.setUpdateBy(userName);
        resources.setUpdateTime(DateUtil.date().toTimestamp());
        cgCustomertableService.update(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping
    @Log("删除客户表")
    @ApiOperation("删除客户表")
    @PreAuthorize("@el.check('cgCustomertable:del')")
    public ResponseEntity<Object> deleteCgCustomertable(@RequestBody List<Integer> ids) {
        for(Integer id:ids){
            CgCustomertable cgCustomertable = cgCustomertableService.getById(id);
            cgCluetableService.deleteByPhone(cgCustomertable.getCustomerTel());
            cgCustomertableService.deleteByPhone(cgCustomertable.getCustomerTel());
            cgDesignService.deleteByPhone(cgCustomertable.getCustomerTel());
            cgFollowupformService.deleteByPhone(cgCustomertable.getCustomerTel());
            cgSigningformService.deleteByPhone(cgCustomertable.getCustomerTel());
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/findByid/{id}")
    @Log("详情客户")
    @ApiOperation("详情客户")
    public ResponseEntity<CgCustomertable> findCgCluetable(@PathVariable("id") Long id){
        CgCustomertable cgCustomertable= cgCustomertableService.getById(id);
        List<CgFollowupform> listFoll = cgFollowupformService.findByPhone(cgCustomertable.getCustomerTel());
        cgCustomertable.setListFoll(listFoll);
        if(!listFoll.isEmpty()){
            cgCustomertable.setLatestFollowPerson(listFoll.get(0).getLatestFollowPerson());
            cgCustomertable.setLatestFollowTime(listFoll.get(0).getCreateTime());
        }
        List<CgSigningform> listSign = cgSigningformService.findByPhone(cgCustomertable.getCustomerTel());
        double signAmount = 0.0;
        for(CgSigningform cgSigningform:listSign){
            signAmount = signAmount + cgSigningform.getSignAmount();
        }
        cgCustomertable.setSignAmount(signAmount);
        cgCustomertable.setListSign(listSign);
        return new ResponseEntity<>(cgCustomertable,HttpStatus.OK);
    }

    @PostMapping(value = "/check")
    @Log("校验客户")
    @ApiOperation("校验客户")
    public ResponseEntity<Object> check(@Validated @RequestBody CgCheckVo resources){
        Integer count = cgCustomertableService.telCount(resources.getCustomerTel());
        if(count>0){
            return new ResponseEntity<>(HttpStatus.LOCKED);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/count")
    @Log("客户统计")
    @ApiOperation("客户统计")
    public ResponseEntity<CgCustomertableCountDTO> count(CgCustomertableQueryCriteria criteria){
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        Integer level = userDetails.getLevel();
        if (userDetails.getUser().getIsAdmin() ||level == 1||level == 2) {
        }else if (level == 3) {
            UserQueryCriteria userCriteria = new UserQueryCriteria();
            Long deptId = userDetails.getUser().getDept().getId();
            List<Dept> data = deptService.findByPid(deptId);
            // 然后把子节点的ID都加入到集合中
            userDetails.getDataScopes().get(0);
            List<Long> deptIds = deptService.getDeptChildren(data);
            deptIds.add(deptId);
            deptIds.add(0L);
            deptIds.retainAll(userDetails.getDataScopes());
            userCriteria.getDeptIds().addAll(deptIds);
            criteria.getDeptIds().addAll(deptIds);

            List<User> listUser = userService.queryAll(userCriteria);
            criteria.setCreateBys(listUser.stream().map(User::getUsername).collect(Collectors.toList()));

        }else if (level == 4) {
            UserQueryCriteria userCriteria = new UserQueryCriteria();
            Long deptId = userDetails.getUser().getDept().getId();
            List<Dept> data = deptService.findByPid(deptId);
            // 然后把子节点的ID都加入到集合中
            userDetails.getDataScopes().get(0);
            List<Long> deptIds = deptService.getDeptChildren(data);
            deptIds.add(deptId);
            deptIds.retainAll(userDetails.getDataScopes());
            userCriteria.getDeptIds().addAll(deptIds);
            criteria.getDeptIds().addAll(deptIds);
            List<User> listUser = userService.queryAll(userCriteria);
            criteria.setCreateBys(listUser.stream().map(User::getUsername).collect(Collectors.toList()));
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }
        List<CgCustomertable>  list = cgCustomertableService.queryAll(criteria);
        Long follow = list.stream().filter(cgCluetable -> "2".equals(cgCluetable.getFollowStatus())).count();
        Long potential = list.stream().filter(cgCluetable -> "1".equals(cgCluetable.getCustomerStatus())).count();
        Long negot = list.stream().filter(cgCluetable -> "2".equals(cgCluetable.getCustomerStatus())).count();

        Long sign = list.stream().filter(cgCluetable -> "2".equals(cgCluetable.getSignStatus())).count();
        list.stream().filter(cgCluetable -> "2".equals(cgCluetable.getFollowStatus())).count();
        CgCustomertableCountDTO cgCustomertableCountDTO = new CgCustomertableCountDTO(list.size(),Integer.valueOf(follow.toString()),Integer.valueOf(potential.toString()),Integer.valueOf(negot.toString()),Integer.valueOf(sign.toString()));
        return new ResponseEntity<>(cgCustomertableCountDTO,HttpStatus.OK);
    }

    @PutMapping(value = "updateCgCluetable")
    @Log("修改客户类型")
    @ApiOperation("修改客户类型")
    public ResponseEntity<Object> updateCgCluetable(@Validated @RequestBody CgNatureVo resources){

        CgCustomertable entity = this.cgCustomertableService.getById(resources.getId());
        entity.setCustomerFlag(resources.getCustomerFlag());
        entity.setDeptId(resources.getDeptId());
        entity.setDeptName("1".equals(resources.getCustomerFlag())?resources.getDeptName():"公海");
        entity.setUpdateTime(DateUtil.date().toTimestamp());
        cgCustomertableService.update(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping(value = "/updateMessage")
    @Log("修改消息成已读")
    @ApiOperation("修改消息成已读")
    public ResponseEntity<Object> updateMessage(@Validated @RequestBody CgCustomertable resources){
        CgCustomertable entity = this.cgCustomertableService.getById(resources.getId());
        entity.setMessageStatus("2");
        cgCustomertableService.update(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}